<?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Album\Model\Album;
use Album\Form\AlbumForm;


class AlbumController extends AbstractActionController
{
	protected $albumTable;


	public function indexAction()
    {
		return new ViewModel(array(
            'albums' => $this->getAlbumTable()->fetchAll(),
        ));
    }

    public function addAction()
    {
		$form = new AlbumForm();
		$form->get('submit')->setValue('Add');

		$request = $this->getRequest();
		
		if ($request->isPost()){
			$album = new Album();
			$form->setInputFilter($album->getInputFilter());
			$form->setData($request->getPost());
			
			if($form->isValid()) {
				$album->exchangeArray($form->getData());
				$this->getAlbumTable()->saveAlbum($album);
				return $this->redirect()->toRoute('album');
			} else {
				
			}
		}
		return array('form' => $form);
    }

    public function editAction()
    {
		$id = $this->params()->fromRoute('id');
		$album = $this->getAlbumTable()->getAlbum($id);	
		
		if(!$album)
		{
			return new ViewModel(array(
				'message' => 'Could not found album id ' . $id,
			));
		}
		$form = new AlbumForm();
		$form->get('id')->setValue($album->id);
		$form->get('artist')->setValue($album->artist);
		$form->get('title')->setValue($album->title);
		$form->get('submit')->setAttributes(array(
			'value' => 'Save',
			'class' => 'btn btn-success',
		));
		
		$request = $this ->getRequest();
		
		if($request->isPost()) {
			if($form->isValid()) {
				$album->exchangeArray($form->getData());
				
				
				// use transaction 
				
				
				$sm = $this->getServiceLocator();
				/* @var $dbAdapter \Zend\Db\Adapter\Adapter */
				
				$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
				
				/* @var $driver \Zend\Db\Adapter\Driver */
				$driver = $dbAdapter->getDriver();
				/* @var $connection \Zend\Db\Adapter\Driver\ConnectionInterface */
				$connection = $driver->getConnection();
				try {
					$connection->beginTransaction();
					$this->getAlbumTable()->saveAlbum($album);
					$connection->commit();
				} catch (\Exception $ex) {
					$connection->rollback();
				}
			}
			return $this->redirect()->toRoute('album');
		}
		
		return array('form' => $form);
					
    }

    public function deleteAction()
    {
		$id = $this->params()->fromRoute('id');
		$album = $this->getAlbumTable()->deleteAlbum($id);
		return $this->redirect()->toRoute('album');
		
    }
	
	public function getAlbumTable()
    {
        if (!$this->albumTable) {
            $sm = $this->getServiceLocator();
            $this->albumTable = $sm->get('Album\Model\AlbumTable');
        }
        return $this->albumTable;
    }
	
	
}